package org.example.back.service.health;

import org.example.back.entity.health.ChronicDisease;
import org.example.back.mapper.health.ChronicDiseaseMapper;
import org.example.back.service.user.UserProfileService;
import org.example.back.entity.user.UserProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ChronicDiseaseService {

    @Autowired
    private ChronicDiseaseMapper chronicDiseaseMapper;

    @Autowired
    private UserProfileService userProfileService;

    // 保存慢性病记录
    @Transactional
    public boolean saveChronicDisease(ChronicDisease chronicDisease) {
        try {
            // 检查用户是否存在
            UserProfile userProfile = userProfileService.getUserProfileByUserId(chronicDisease.getUserId());
            if (userProfile == null) {
                return false;
            }

            // 如果用户角色不是慢性病患者，则更新用户角色
            if (!"慢性病患者".equals(userProfile.getRoleTag())) {
                userProfile.setRoleTag("慢性病患者");
                userProfileService.updateUserProfile(userProfile);
            }

            chronicDiseaseMapper.insertChronicDisease(chronicDisease);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 根据用户ID获取慢性病记录列表
    public List<ChronicDisease> getChronicDiseasesByUserId(Integer userId) {
        return chronicDiseaseMapper.findChronicDiseasesByUserId(userId);
    }

    // 根据ID获取慢性病记录
    public ChronicDisease getChronicDiseaseById(Integer id) {
        return chronicDiseaseMapper.findChronicDiseaseById(id);
    }

    // 更新慢性病记录
    @Transactional
    public boolean updateChronicDisease(ChronicDisease chronicDisease) {
        try {
            chronicDiseaseMapper.updateChronicDisease(chronicDisease);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 删除慢性病记录
    @Transactional
    public boolean deleteChronicDisease(Integer id) {
        try {
            chronicDiseaseMapper.deleteChronicDisease(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}